/***************************************************************************
 *   Copyright (C) 2009 by mj   *
 *   mj_dv@web.de   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

// firstStart.cpp is a part of the steamserverutil project it is the GUI using Qt 4 for the console app steamserverutil
// steamserverutil.googlecode.com

#include <QFileDialog>
#include <QMessageBox>
#include <QNetworkRequest>
#include <QUrl>
#include <QByteArray>
#include <QIODevice>
#include <QFile>



#include "firststart.h"
#include "steamserverutil.h"



firstStart::firstStart(QWidget *parent) :
    QWizard(parent)
{
   setupUi(this);
   setStartId(0);

   connect(openButton, SIGNAL(clicked()), this, SLOT(open()));
   connect(this, SIGNAL(currentIdChanged(int)), this, SLOT(id_changed(int)));

   progressBar->setValue(0);

   installPathEdit->setText((QString)util.get_home().c_str()+"/.steamserverutil");

   proc = new QProcess;
}

void firstStart::open()
{
    QString dir = QFileDialog::getExistingDirectory(this, tr("Install to .. "), installPathEdit->text());
    if(!dir.isEmpty())
        installPathEdit->setText(dir);
}



void firstStart::id_changed(int i)
{

    switch(i)
    {

        case 2:
            if(importCheckBox->isChecked())
            {
                util.get_old_workspace();
                QString wdir = util.workdir.c_str();
                if(wdir == "nodir")
                {
                    back();
                    QMessageBox::critical(this, tr("Error"), tr("Something went wrong with importing the \"old\" workspace!"), QMessageBox::Ok | QMessageBox::Default);
                }
                else
                {
                   this->accept();
                   util.set_workspace(wdir);
                }


                break;
            }

            if(installPathEdit->text().isEmpty())
            {
                back();
                QMessageBox::critical(this, tr("Error"), tr("Invalid install Path!"), QMessageBox::Ok | QMessageBox::Default);

            }
            else
                download();
            break;
        case 3: extract();
            break;
        case 4:
            if(!licenseCheckBox->isChecked())
                {
                    back();
                    QMessageBox::critical(this, tr("Error"), tr("Please accept the license!"), QMessageBox::Ok | QMessageBox::Default);

                }
                else
                {
                    proc->write("yes");
                    util.set_workspace(installPathEdit->text());
                }
                break;


    }

}

void firstStart::download()
{
     manager = new QNetworkAccessManager(this);
     reply = manager->get(QNetworkRequest(QUrl("http://www.steampowered.com/download/hldsupdatetool.bin")));

     connect(reply, SIGNAL(downloadProgress(qint64, qint64)), this, SLOT(set_progress(qint64, qint64)));
     connect(reply, SIGNAL(finished()), this, SLOT(save()));



}

void firstStart::set_progress(qint64 cur, qint64 max)
{
    progressBar->setMaximum(max);
    progressBar->setValue(cur);
}

void firstStart::save()
{
    QByteArray data = reply->readAll();

    QString path = installPathEdit->text();
    QDir dir(path);
    if(!dir.exists())
        dir.mkdir(path);


    QFile out(path+"/hldsupdatetool.bin");

    if (!out.open(QIODevice::WriteOnly))
    {
        QMessageBox::critical(this, tr("Error writing data"), tr("Cannot write data: "), QMessageBox::Ok | QMessageBox::Default);
        return;
    }
    out.write(data);

    downLabel->setText("Finished!");

}

void firstStart::extract()
{


    proc->setWorkingDirectory(installPathEdit->text());

    QProcess temp;
    temp.start("chmod +x hldsupdatetool.bin");

    proc->start(installPathEdit->text() + "/hldsupdatetool.bin");

    connect(proc, SIGNAL(readyReadStandardOutput()), this, SLOT(read()));

}

void firstStart::read()
{
    textBrowser->setText(proc->readAllStandardOutput());
}

void firstStart::on_importCheckBox_stateChanged(int state)
{
    if(state == Qt::Checked)
    {
        installPathEdit->setEnabled(false);
        openButton->setEnabled(false);
    }
    else
    {
        installPathEdit->setEnabled(true);
        openButton->setEnabled(true);
    }
}


/*int firstStart::nextId() const
{
    switch(currentId())
    {
        case 0: return 1;
        case 1:
            return 2;
        case 2: return 3;
        case 3: return 4;
        case 4: // return -1
        default: return -1;
    }
}*/




